package models

import (
	"github.com/astaxie/beego/orm"
	"strconv"
	"time"
)

type MessageModels struct{}

type Message struct {
	Message_id int64 `orm:"pk;auto;size(11);"`
	Title      string
	Tel        string `orm:size(12)`
	Addtime    int64  `orm:default(0)`
	Open       int    `orm:size(2);default(0)`
	Ip         string `orm:size(30)`
	Content    string
	Name       string `orm:size(50)`
	Email      string `orm:size(200)`
	Is_read    int    `orm:size(1);default(0)`
}

func init() {
	orm.RegisterModel(new(Message))
}

// 获取指定ID的信息
func (m *MessageModels) Get(mid int64) (Message, error) {
	mess := Message{}
	mess.Message_id = mid
	o := orm.NewOrm()
	err := o.Read(&mess)
	return mess, err
}

//列表
func (m *MessageModels) QueryByPage(maps map[string]interface{}) ([]Message, int64) {
	var list []Message
	o := orm.NewOrm()
	ps := o.QueryTable("message")
	if maps["limit"] == nil {
		maps["limit"] = 10
	}
	if maps["page"] == nil {
		maps["page"] = 1
	}
	if maps["tel"] != nil {
		ps = ps.Filter("tel", maps["tel"])
	}
	if maps["open"] != nil {
		ps = ps.Filter("open", maps["open"])
	}
	if maps["ip"] != nil {
		ps = ps.Filter("ip", maps["ip"])
	}
	if maps["name"] != nil {
		ps = ps.Filter("name", maps["name"])
	}
	if maps["email"] != nil {
		ps = ps.Filter("email", maps["email"])
	}
	if maps["is_read"] != nil {
		ps = ps.Filter("is_read", maps["is_read"])
	}

	page, _ := maps["page"].(int)
	limit, _ := maps["limit"].(int)
	off := (page - 1) * limit

	ps.Limit(limit, off).All(&list)
	count, _ := ps.Count()
	return list, count
}

//添加
func (m *MessageModels) Insert(maps map[string]interface{}) (int64, error) {
	mess := Message{}
	if maps["title"] != nil {
		mess.Title = maps["title"].(string)
	}
	if maps["tel"] != nil {
		mess.Tel = maps["tel"].(string)
	}
	if maps["ip"] != nil {
		mess.Ip = maps["ip"].(string)
	}
	if maps["content"] != nil {
		mess.Content = maps["content"].(string)
	}
	if maps["name"] != nil {
		mess.Name = maps["name"].(string)
	}
	if maps["email"] != nil {
		mess.Email = maps["email"].(string)
	}
	mess.Addtime = time.Now().Unix()

	o := orm.NewOrm()
	return o.Insert(&mess)
}

//更新
func (m *MessageModels) Update(maps map[string]interface{}) (int64, error) {
	mess := Message{}
	mess.Message_id, _ = strconv.ParseInt(maps["message_id"].(string), 10, 64)
	o := orm.NewOrm()
	o.Read(&mess)
	if maps["open"] != nil {
		mess.Open, _ = strconv.Atoi(maps["open"].(string))
	}
	if maps["is_read"] != nil {
		mess.Is_read, _ = strconv.Atoi(maps["is_read"].(string))
	}
	return o.Update(&mess)
}

//删除
func (m *MessageModels) Delete(mid int64) (int64, error) {
	mess := Message{}
	mess.Message_id = mid
	o := orm.NewOrm()
	return o.Delete(&mess, "message_id")
}
